import { Button, Col, Form, Input, message, Modal, Row } from 'antd'
import cs from 'classnames'
import { useEffect, useState } from 'react'

import { ComplianceDetails } from '@/api/interface/user'
import { ComplianceCreate, ComplianceUpdate } from '@/api/modules/user'
import locale from '@/pages/user/locale'
import styles from '@/pages/user/style/index.module.less'
import useLocale from '@/utils/useLocale'

const handleInputChange = (event: any) => {
  const { value } = event.target
  event.target.value = value.trim().replace(/[^0-9]/g, '')
}

function Create({
  isModalOpen,
  setIsModalOpen,
  record,
  onRefresh,
}: {
  isModalOpen: boolean
  setIsModalOpen: (_: boolean) => void
  record: any
  onRefresh: () => void
}) {
  const t = useLocale(locale)
  const [loadig, setLoading] = useState<boolean>(false)
  const [messageApi] = message.useMessage()
  const handleOk = () => {
    form.validateFields().then((values) => {
      setLoading(true)
      if (record.id) {
        ComplianceUpdate({ ...formParams, ...values, id: record.id })
          .then(() => {
            form.resetFields()
            setLoading(false)
            messageApi.open({
              type: 'success',
              content: t['update.success'],
            })
            setIsModalOpen(false)
            onRefresh()
          })
          .catch(() => {
            setLoading(false)
          })
        return
      }
      ComplianceCreate({ ...formParams, ...values })
        .then(() => {
          form.resetFields()
          setLoading(false)
          messageApi.open({
            type: 'success',
            content: t['create.success'],
          })
          setIsModalOpen(false)
          onRefresh()
        })
        .catch(() => {
          setLoading(false)
        })
    })
  }
  const handleCancel = () => {
    setIsModalOpen(false)
  }

  const title = (
    <>
      <div className={cs('text-[22px] font-bold Roboto pt-1 pb-7')}>
        {record.id ? t['update.title'] : t['create.title.add']}
      </div>
    </>
  )

  const footer = (
    <div className={cs('flex justify-end')}>
      <Button loading={loadig} type="primary" className={cs(styles['add'])} onClick={handleOk}>
        <span className="Roboto text-[14px] font-bold">{t['form.add']}</span>
      </Button>
    </div>
  )

  const [form] = Form.useForm()
  const [formParams, setFormParams] = useState<ComplianceDetails>({
    active: true,
    admin: false,
    email: '',
    // emirate: '',
    // entityId: null,
    // id: null,
    jobDescription: '',
    mobile: '',
    officerName: '',
    officerNameAr: '',
    officerNumber: '',
  })

  useEffect(() => {
    if (isModalOpen) {
      form.resetFields()
      setLoading(false)
      if (record.id) {
        setFormParams((a) => ({
          ...a,
          active: Boolean(record.active),
          admin: Boolean(record.admin),
        }))
        form.setFieldsValue({
          email: record.email,
          jobDescription: record.jobDescription,
          mobile: record.mobile,
          officerName: record.officerName,
          officerNameAr: record.officerNameAr,
          officerNumber: record.officerNumber,
        })
      }
    }
  }, [isModalOpen])

  return (
    <Modal
      centered
      title={title}
      open={isModalOpen}
      onCancel={handleCancel}
      wrapClassName={styles['create-wrapper']}
      footer={footer}
      width="700px"
    >
      <Form
        layout="vertical"
        autoComplete="off"
        form={form}
        initialValues={formParams}
        validateMessages={{
          required: () => t['create.empty'],
        }}
        validateTrigger="onBlur"
      >
        <Row gutter={24}>
          <Col span={12}>
            <Form.Item label={t['create.name']} rules={[{ required: true }]} name="officerName">
              <Input placeholder={t['create.name']} maxLength={100} allowClear />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={t['create.email']}
              rules={[
                {
                  required: true,
                },
                {
                  validator: async (_, val) => {
                    if (val) {
                      if (
                        !/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/.test(
                          val
                        )
                      ) {
                        return Promise.reject(new Error(t['create.email.message']))
                      }
                      // 判断是否是私人邮箱
                      const personalEmailDomains = [
                        'gmail.com',
                        'outlook.com',
                        'yahoo.com',
                        'icloud.com',
                        'protonmail.com',
                        'aol.com',
                        'gmx.com',
                        'zoho.com',
                        'outlook.com',
                        'hotmail.com',
                        'Mail.com',
                        'gmx.com',
                        'yandex.com',
                        'naver.com',
                        'daum.net',
                        'tuta.com',
                      ]
                      const domain = val.split('@')[1]
                      if (personalEmailDomains.includes(domain.toLowerCase())) {
                        return Promise.reject(new Error(t['create.email.message1']))
                      }
                    }
                  },
                },
              ]}
              name="email"
            >
              <Input placeholder={t['create.email']} allowClear disabled={record?.id} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={t['create.nameAr']} rules={[{ required: true }]} name="officerNameAr">
              <Input placeholder={t['create.nameAr']} maxLength={100} allowClear />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={t['create.mobile']}
              rules={[
                { required: true },
                {
                  validator: async (_, val) => {
                    if (val) {
                      if (!/^05\d{8}$/.test(val)) {
                        return Promise.reject(new Error(t['create.mobile.message']))
                      }
                      if (val.length != 10) {
                        return Promise.reject(new Error(t['create.mobile.message1']))
                      }
                    }
                  },
                },
              ]}
              name="mobile"
            >
              <Input placeholder={t['create.mobile']} maxLength={10} allowClear />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={t['create.officer']}
              rules={[
                { required: true },
                {
                  validator: async (_, val) => {
                    if (val) {
                      if (!/^\d{9,12}$/.test(val)) {
                        return Promise.reject(new Error(t['create.officer.message']))
                      }
                    }
                  },
                },
              ]}
              name="officerNumber"
            >
              <Input
                placeholder={t['create.officer']}
                maxLength={12}
                allowClear
                onInput={handleInputChange}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={t['create.jonDesc']}
              rules={[{ required: true }]}
              name="jobDescription"
            >
              <Input placeholder={t['create.jonDesc']} maxLength={100} allowClear />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  )
}
export default Create
